package com.rocksea.app.fragment;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.TypedValue;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.rocksea.app.BaseFragment;
import com.rocksea.app.R;
import com.rocksea.app.activity.BaseShowActivity;
import com.rocksea.app.activity.HighStrainActivity;
import com.rocksea.app.activity.LowStrainActivity;
import com.rocksea.app.activity.SonicWaveActivity;
import com.rocksea.app.activity.StaticLoadActivity;
import com.rocksea.app.db.DbCenter;
import com.rocksea.app.db.UpLoadingTable;
import com.rocksea.app.db.UploadingDbHelper;
import com.rocksea.app.db.history.HistoryTable;
import com.rocksea.app.event.DeleteEvent;
import com.rocksea.app.event.ViewPileEvent;
import com.rocksea.app.tasks.LoadHistoryTask;
import com.rocksea.app.utils.PerUtils;
import com.rocksea.app.utils.UiUtils;
import com.rocksea.app.weight.DoubleDatePickerDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.Map;
import java.util.TreeMap;

import butterknife.InjectView;

public class ExpandableListFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, RadioGroup.OnCheckedChangeListener {

    @InjectView(R.id.status_bar) View mStatus;
    @InjectView(R.id.Edit) ImageView mEdit;
    @InjectView(R.id.Delete) TextView mDelete;
    @InjectView(R.id.UpLoad) TextView mUpLoad;
    @InjectView(R.id.SwipeRefreshLayout) SwipeRefreshLayout mRefreshLayout;
    @InjectView(R.id.Title) TextView mTitle;
    @InjectView(R.id.History_Table) ExpandableListView mExpandableListView;

    @InjectView(R.id.Radio_Group_Layout) View mRadioGroupLayout;
    @InjectView(R.id.Radio_Group) RadioGroup mRadioGroup;
    @InjectView(R.id.Test_DY) RadioButton mDyRadio;
    @InjectView(R.id.Test_GY) RadioButton mGyRadio;
    @InjectView(R.id.Test_SC) RadioButton mSCRadio;
    @InjectView(R.id.Test_JZ) RadioButton mJZRadio;
    @InjectView(R.id.Test_All) RadioButton mALLRadio;

    private Map<String,ArrayList<HistoryTable>> mHistoryData = new TreeMap<>();
    private int pageIndex = 7;
    private PopupMenu popupMenu;
    private ExpandableListViewAdapter mExpandableListViewAdapter;
    private int mTestingMode = HistoryTable.TEST_ALL;

    public static ExpandableListFragment newInstance()
    {
        Bundle args = new Bundle();
        ExpandableListFragment fragment = new ExpandableListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initView()
    {
        EventBus.getDefault().register(this);
        mStatus.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                getStateBarHeight(getActivity())));
        mRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
        mRefreshLayout.setOnRefreshListener(this);

        mRadioGroup.setOnCheckedChangeListener(this);

        mExpandableListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                boolean enable = false;
                if (view != null && view.getChildCount() > 0) {
                    boolean firstItemVisible = view.getFirstVisiblePosition() == 0;
                    boolean topOfFirstItemVisible = view.getChildAt(0).getTop() == 0;
                    enable = firstItemVisible && topOfFirstItemVisible;
                }
                mRefreshLayout.setEnabled(enable);
            }
        });

        mExpandableListView.setGroupIndicator(null);
        mExpandableListViewAdapter = new ExpandableListViewAdapter();
        mExpandableListView.setAdapter(mExpandableListViewAdapter);
        mEdit.setOnClickListener(moreListener);
        mALLRadio.setChecked(true);

        popupMenu = new PopupMenu(getContext(),mEdit);
        popupMenu.getMenuInflater().inflate(R.menu.history, popupMenu.getMenu());
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item)
            {
                switch (item.getItemId())
                {
                    case R.id.one_month:
                        pageIndex = 7;
                        mTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
                        mTitle.setText("最近7天");
                        item.setChecked(true);
                        mRefreshLayout.setRefreshing(true);
                        requestRefresh();
                        return true;

                    case R.id.two_month:
                        pageIndex = 15;
                        mTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
                        mTitle.setText("最近15天");
                        item.setChecked(true);
                        mRefreshLayout.setRefreshing(true);
                        requestRefresh();
                        return true;

                    case R.id.three_month:
                        pageIndex = 30;
                        mTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
                        mTitle.setText("最近30天");
                        item.setChecked(true);
                        mRefreshLayout.setRefreshing(true);
                        requestRefresh();
                        return true;

                    case R.id.Time:
                        item.setChecked(true);
                        DoubleDatePickerDialog doubleDatePickerDialog = new DoubleDatePickerDialog(getContext());
                        doubleDatePickerDialog.setOnDateSetListener(mOnDateSetListener);
                        doubleDatePickerDialog.setStartDate(new Date().getTime()- DbCenter.DAY_OF_TIME);
                        doubleDatePickerDialog.setEndDate(new Date().getTime()+DbCenter.DAY_OF_TIME);
                        doubleDatePickerDialog.show();
                        return true;
                }
                return false;
            }
        });
    }

    private ImageView.OnClickListener moreListener = new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {
            popupMenu.show();
        }
    };

    @Override
    public void onDestroy()
    {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    private void requestRefresh()
    {
        LoadHistoryTask.startLoadHistoryTask(pageIndex,mQueryCallBack,mTestingMode);
    }

    private LoadHistoryTask.QueryCallBack mQueryCallBack = new LoadHistoryTask.QueryCallBack()
    {
        @Override
        public void onQueryCallBack(Map<String, ArrayList<HistoryTable>> tables)
        {
            mRefreshLayout.setRefreshing(false);
            loadCompleted();
            if (tables == null || tables.size() == 0)
            {
                loadFailed();
                mErrorText.setText("未查询到数据");
                return;
            }
            mHistoryData.clear();
            mHistoryData.putAll(tables);
            mExpandableListViewAdapter.refreshList();
        }
    };

    private DoubleDatePickerDialog.OnDateSetListener mOnDateSetListener = new DoubleDatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(long start, long end)
        {
            mTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
            if (start < end)
            {
                mTitle.setText(String.format("%s至%s",PerUtils.dateToDay(new Date(start)),PerUtils.dateToDay(new Date(end))));
                LoadHistoryTask.startLoadHistoryTask(end,start,mQueryCallBack,mTestingMode);
            }
            else
            {
                mTitle.setText(String.format("%s至%s",PerUtils.dateToDay(new Date(end)),PerUtils.dateToDay(new Date(start))));
                LoadHistoryTask.startLoadHistoryTask(start,end,mQueryCallBack,mTestingMode);
            }
        }
    };

    @Override
    protected void initData()
    {
        loading();
        requestRefresh();
    }


    @Override
    protected void requestAgain()
    {
        loading();
        requestRefresh();
    }

    @Override
    protected int getContentViewId()
    {
        return R.layout.expanable_list_fragment;
    }

    @Override
    public void onRefresh()
    {
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                requestRefresh();
            }
        }, 1000);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId)
    {
        switch (checkedId)
        {
            case R.id.Test_DY:
                mTestingMode = HistoryTable.TEST_DY;
                //mExpandableListViewAdapter.notificationChooseTestMode(HistoryTable.TEST_DY);
                break;

            case R.id.Test_SC:
                mTestingMode = HistoryTable.TEST_SC;
                //mExpandableListViewAdapter.notificationChooseTestMode(HistoryTable.TEST_SC);
                break;

            case R.id.Test_All:
                mTestingMode = HistoryTable.TEST_ALL;
               //mExpandableListViewAdapter.notificationChooseTestMode(HistoryTable.TEST_ALL);
                break;

            case R.id.Test_JZ:
                mTestingMode = HistoryTable.TEST_JZ;
                //mExpandableListViewAdapter.notificationChooseTestMode(HistoryTable.TEST_JZ);
                break;

            case R.id.Test_GY:
                mTestingMode = HistoryTable.TEST_GY;
                //mExpandableListViewAdapter.notificationChooseTestMode(HistoryTable.TEST_GY);
                break;
        }
        requestRefresh();
    }

    private class ExpandableListViewAdapter extends BaseExpandableListAdapter
    {
        private ArrayList<String> group = new ArrayList<>();



        ExpandableListViewAdapter()
        {
            for (Map.Entry<String, ArrayList<HistoryTable>> stringArrayListEntry : mHistoryData.entrySet())
            {
                group.add(stringArrayListEntry.getKey());
            }
        }

        private void refreshList()
        {
            group.clear();
            for (Map.Entry<String, ArrayList<HistoryTable>> stringArrayListEntry : mHistoryData.entrySet())
            {
                group.add(stringArrayListEntry.getKey());
            }
            notifyDataSetChanged();
        }

        @Override
        public int getGroupCount()
        {
            if (mHistoryData.size() == 0)
                return 0;
            return mHistoryData.size();
        }

        @Override
        public int getChildrenCount(int groupPosition)
        {
            return mHistoryData.get(group.get(groupPosition)).size();
        }

        @Override
        public Object getGroup(int groupPosition)
        {
            return group.get(groupPosition);
        }

        @Override
        public Object getChild(int groupPosition, int childPosition)
        {
            return mHistoryData.get(group.get(groupPosition)).get(childPosition);
        }

        @Override
        public long getGroupId(int groupPosition)
        {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition)
        {
            return childPosition;
        }

        @Override
        public boolean hasStableIds()
        {
            return false;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
        {
            if (convertView==null)
                convertView = View.inflate(getContext(),R.layout.expandable_listview_group_item,null);
            TextView mGroupTV = (TextView) convertView.findViewById(R.id.Group_Title);
            View tableTitle = convertView.findViewById(R.id.table_title);
            ImageView mGroupIndicator = (ImageView) convertView.findViewById(R.id.sample_activity_list_group_expanded_image);
            mGroupTV.setText(group.get(groupPosition));
            if (isExpanded)
            {
                tableTitle.setVisibility(View.VISIBLE);
                mGroupIndicator.setImageResource(R.mipmap.ic_arrow_up);
            }
            else
            {
                tableTitle.setVisibility(View.GONE);
                mGroupIndicator.setImageResource(R.mipmap.ic_arrow_down);
            }
            return convertView;
        }

        @Override
        public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
        {
            if (convertView==null)
                convertView = View.inflate(getContext(),R.layout.pile_file_list_item_layout,null);
            TextView pileNo = (TextView) convertView.findViewById(R.id.Pile_No);
            TextView testMode = (TextView) convertView.findViewById(R.id.Test_Name);
            TextView testTime = (TextView) convertView.findViewById(R.id.Test_Time);
            ImageView state = (ImageView) convertView.findViewById(R.id.State);
            View item = convertView.findViewById(R.id.List_Title);
            final HistoryTable historyTable = mHistoryData.get(group.get(groupPosition)).get(childPosition);
            item.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v)
                {
                    showDialog(historyTable);
                    return true;
                }
            });

            item.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    openPileInfo(groupPosition,childPosition);
                }
            });

            if (historyTable.getPileNo()==null)
                pileNo.setText("--");
            else
                pileNo.setText(historyTable.getPileNo());
            Date date = new Date(historyTable.CreatTime);
            String creatTime = PerUtils.dateToStr(date);
            testTime.setText(creatTime);
            switch (historyTable.IsLoad)
            {
                case 0:
                    state.setImageDrawable(ContextCompat.getDrawable(getContext(),R.mipmap.ic_upload_action));
                    testMode.setText("-");
                    break;
                case 1:
                    testMode.setText(PerUtils.dateToStr(new Date(historyTable.LoadTime)));
                    state.setImageDrawable(ContextCompat.getDrawable(getContext(),R.mipmap.ic_upload_ok));
                    break;
            }

            state.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View view)
                {
                    //动测就算上传了 也可以再次添加到队列中
                    if (historyTable.IsLoad == 1 && historyTable.Type != HistoryTable.TEST_DY)
                    {
                        UiUtils.showToast("数据已上传");
                        return;
                    }
                    // 添加到上传队列中
                    UpLoadingTable upLoadingTable = new UpLoadingTable();
                    upLoadingTable.baseInfoId = historyTable.BaseInfoId;
                    upLoadingTable.mode = historyTable.Type;
                    upLoadingTable.pileNo = historyTable.getPileNo();
                    upLoadingTable.planNum = historyTable.getSerialNo();
                    upLoadingTable.uuid = UpLoadingTable.DEFAULT_UUID;
                    if (UploadingDbHelper.insert(upLoadingTable) == 0)
                    {
                        UiUtils.showToast("已添加到了上传队列");
                    }
                    else
                    {
                        UiUtils.showToast("上传队列已存在");
                    }
                }
            });
            return convertView;
        }

        private void showDialog(final HistoryTable historyTable)
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle("提示");
            builder.setMessage("确定要删除吗?");
            builder.setPositiveButton("删除", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    dialog.dismiss();
                    ArrayList<HistoryTable> toDeleteList = new ArrayList<>();
                    toDeleteList.add(historyTable);
                    DeleteEvent deleteEvent = new DeleteEvent();
                    deleteEvent.setEventType(DeleteEvent.START_DELETE);
                    deleteEvent.setHistoryTables(toDeleteList);
                    EventBus.getDefault().post(deleteEvent);
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.show();


        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition)
        {

            return false;
        }

        private void openPileInfo(int groupPosition,int childPosition)
        {
            String serialNo = (String) getGroup(groupPosition);
            ArrayList<HistoryTable> historyTables = mHistoryData.get(serialNo);
            HistoryTable historyTable = historyTables.get(childPosition);
            Intent intent;
            switch (historyTable.getType()){
                case HistoryTable.TEST_DY:
                    intent = new Intent(getContext(), LowStrainActivity.class);
                    break;
                case HistoryTable.TEST_GY:
                    intent = new Intent(getContext(), HighStrainActivity.class);
                    break;
                case HistoryTable.TEST_SC:
                    intent = new Intent(getContext(), SonicWaveActivity.class);
                    break;
                case HistoryTable.TEST_JZ:
                    intent = new Intent(getContext(), StaticLoadActivity.class);
                    break;
                default:
                    intent = new Intent(getContext(), LowStrainActivity.class);
                    break;
            }
            String[] pileInfo = new String[]{historyTable.getSerialNo(),historyTable.getPileNo(),historyTable.BaseInfoId};
            intent.putExtra(BaseShowActivity.INFO_EXTRA_KEY,pileInfo);
            getActivity().startActivity(intent);
        }

        public void delete(ArrayList<HistoryTable> historyTables)
        {
            for (HistoryTable historyTable : historyTables)
            {
                if (mHistoryData.get(historyTable.SerialNo) != null)
                {
                    for (int i = 0; i < mHistoryData.get(historyTable.SerialNo).size(); i++)
                    {
                        if (mHistoryData.get(historyTable.SerialNo).get(i).BaseInfoId.equals(historyTable.BaseInfoId))
                        {
                            mHistoryData.get(historyTable.SerialNo).remove(i);
                        }
                    }
                }
            }
            notifyDataSetChanged();
        }
    }

    private ProgressDialog progressDialog = null;
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDelete(DeleteEvent deleteEvent)
    {
        switch (deleteEvent.getEventType())
        {
            case DeleteEvent.START_DELETE :
                ArrayList<HistoryTable> deleteHistory = deleteEvent.getHistoryTables();
                for (HistoryTable historyTable : deleteHistory)
                {
                    if (historyTable.Type == HistoryTable.TEST_DY)
                    {
                        if (!DbCenter.mDyDbHelper. isAllUploaded(historyTable.BaseInfoId))
                        {
                            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                            builder.setTitle("提示");
                            builder.setIcon(android.R.drawable.ic_dialog_alert);
                            builder.setMessage("无法删除未上传或部分上传的低应变数据");
                            builder.setPositiveButton("确定",null);
                            builder.show();
                            return;
                        }
                    }
                }
                DbCenter.delete(deleteEvent.getHistoryTables());
                progressDialog = ProgressDialog.show(getActivity(),"删除数据","正在删除数据...",false,false);
                break;
            case DeleteEvent.OVER_DELETE:
                if (progressDialog != null)
                {
                    progressDialog.dismiss();
                    mExpandableListViewAdapter.delete(deleteEvent.getHistoryTables());
                    UiUtils.showToast("删除成功");
                }
                break;
        }
    }

}
